#! /usr/bin/env python

# -*- coding: UTF-8 -*-
# ==============================================================================
# Filename : NotificationBox.py
# Purpose  : 
# Author   : Yohann Li (lyh001686@sina.com)
# Date     : 2020-08-19 19:37
# ==============================================================================
from PyQt5.QtCore import QTimer, Qt, QRectF
from PyQt5.QtGui import QFont, QPainter, QFontMetrics
from PyQt5.QtWidgets import QApplication, QLabel
import sys
from conf.configuration import logger, text_color, style
from conf.configuration import NotificationBoxDelaySeconds as delay


class NoteBox(QLabel):
    def __init__(self):
        super(NoteBox, self).__init__()
        self.setObjectName('notebox')
        self.delay = delay * 3000
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.close)
        self.setWindowFlag(Qt.FramelessWindowHint)
        # self.setWindowOpacity(0.5)
        self._color = None
        self.msg = None
        self.setFont(self.set_font())
        self.setContentsMargins(0, 0, 0, 0)

    @staticmethod
    def set_font():
        font = QFont()
        font.setPointSize(30)
        font.setBold(True)
        return font

    def warning(self, _p: str = ''):
        self._color = text_color.get('red')
        self.msg = _p
        self._start_timer(self.msg)
        logger.debug(_p)

    def info(self, _p: str = ''):
        self._color = text_color.get('green')
        self.msg = _p
        self._start_timer(self.msg)
        logger.debug(_p)

    def _start_timer(self, _p: str = ''):
        metrics = QFontMetrics(self.font())
        w = metrics.width(_p)+20
        h = metrics.height()+20
        screen_size = QApplication.desktop().screen().size()
        screen_w = screen_size.width()
        screen_h = screen_size.height()
        self.resize(w, h)
        self.setGeometry(int((screen_w-w)/2), int((screen_h-h)/4), w, h)
        self.show()
        self.timer.start(self.delay)

    def paintEvent(self, a0) -> None:
        painter = QPainter(self)
        painter.setPen(self._color)
        # painter.setPen(self._color)

        painter.setFont(self.font())
        # painter.drawRect(QRectF(0, 0, self.width(), self.height()))
        painter.drawText(QRectF(0, 0, self.width(), self.height()),
                         Qt.AlignCenter, self.msg)

    def mousePressEvent(self, a0) -> None:
        self.close()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyleSheet(style)
    gtf = NoteBox()
    # gtf.resize()
    # gtf.show()
    gtf.warning('1234567890987654321234567890987654321')
    app.exec_()
